package com.tpay.client.entrypoint;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtplatform.mvp.client.DelayedBindRegistry;
import com.tpay.client.gin.GinjectorProvider;
import com.tpay.client.gin.PayGinjector;
import com.tpay.client.i18n.PayConstants;
import com.tpay.client.i18n.PayMessages;
import com.tpay.client.theme.PayClientBundle;
import com.tpay.client.util.I18nUtil;

public abstract class MultiPageEntryPoint implements EntryPoint {
	protected final PayGinjector ginjector = ((GinjectorProvider)GWT.create(GinjectorProvider.class)).get();
	
	@Override
	public void onModuleLoad() {
		GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

			@Override
			public void onUncaughtException(Throwable e) {
				Window.alert("오류발생");
				e.printStackTrace();
				
			}
		});
		
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
			
			@Override
			public void execute() {
				onModuleLoad2();
			}
		});
		
	}

	protected void onModuleLoad2() {
		try {
			bind();
			
			Dictionary dictionary = Dictionary.getDictionary("Pages");
			revealCurrentPlace(dictionary.get("page"));
			
			// hide the animated 'loading.gif'
			RootPanel.get("loading").setVisible(false);
			
		} catch (Exception e) {
			e.printStackTrace();
			Window.alert(e.getLocalizedMessage());
		}
	}
	
	protected void bind() {
		PayClientBundle.INSTANCE.css().ensureInjected();
		
		I18nUtil.init();
		
		// gwt-platform의 프록시 생성에 필요하다.
	    // Main.gwt.xml에 아래 문장이 있어야 한다.
	    //   <define-configuration-property name="gin.ginjector" is-multi-valued="false" />
	    //   <set-configuration-property name="gin.ginjector" value="com.time.pay.client.gin.PayGinjector" />
		DelayedBindRegistry.bind(getPayGinjector());
	}

	protected void revealCurrentPlace(String page) {
		// 메소드를 오버라이드 해야 합니다.
	}

	public static String getRelativeURL(String url) {
		// .html files are located relative to the applications host page
	    // e.g. /modulename/ModuleName.html not
	    //      /modulename/modulename/hosted.html
	    return GWT.getHostPageBaseURL() + url;
	}
	
	public static PayConstants getConstant() {
		return I18nUtil.getConstant();
	}
	
	public static PayMessages getMessage() {
		return I18nUtil.getMessage();
	}
	
	public PayGinjector getPayGinjector() {
		return ginjector;
	}

}
